﻿/*
 * 门诊
 *
*/
var OutPatient = function (schedule, options) {
    var printArr = [],
    scheduleExamRequest = null;

    this.showBack = options.showBack;
    this.thisContainer = options.thisContainer;
    this.backContainer = options.backContainer;

    this.init = function (eventInit) {
        $('#outPaitientContainer').height($(window).height() - 200);

        if (!schedule) {
            schedule = new Schedule("OutPatient", $('#hdnRelativeUrl').val());
            schedule.days = 1;
        }

        schedule.getExamRequestScheduleInfoList(getExamRequestScheduleInfoListCallback);

        if (this.showBack) {
            $('#btnBack').show();
        }

        if (!eventInit)
            pageEventInit();
    };

    this.clear = function () {
        $('.name').text("");
        $('.sex').text("");
        $('.age').text("");
        $('.department').text("");

        $('#outPaitientContainer').html("");
        printNum();
    };

    //获取全部门诊预约
    var getExamRequestScheduleInfoListCallback = function (data) {
        $('.name').text(data[0].Name);
        $('.sex').text(data[0].Sex);
        $('.age').text(data[0].Age + data[0].AgeUnit);
        $('.department').text(data[0].RequestDeptName);
        var html = "";
        $.each(schedule.examRequestList, function (i, n) {
            var bottom_none = (i == schedule.examRequestList.length - 1) ? '' : 'bottom_none';

            html += '<div id="' + n.PlacerOrderNO + '" class="clinic_div ' + bottom_none + '"  data-placerorderno=' + n.PlacerOrderNO + ' >' +
                        appendScheduleRow(n) +
                    '</div>';
        });
        $('#outPaitientContainer').html(html);

        printNum();
    };

    var appendScheduleRow = function (examRequest) {
        var operateBtn = '';
        var checkbox = '';
        var scheduleDate = '';
        var scheduleTime = '';

        if (examRequest.ScheduleStartDate && examRequest.ScheduleEndDate) {
            scheduleDate = examRequest.ScheduleStartDate.substr(0, 10);
            scheduleTime = examRequest.ScheduleStartDate.substr(11, 5) + "-" + examRequest.ScheduleEndDate.substr(11, 5);
        }

        if (examRequest.ScheduleStatus == 0) {
            examRequest.ScheduleFlag = true;
            examRequest.ChangeFlag = false;
            examRequest.OriginalScheduleResourceName = examRequest.ScheduleResourceName;
            examRequest.OriginalScheduleStartDate = examRequest.ScheduleStartDate;
            examRequest.OriginalScheduleEndDate = examRequest.ScheduleEndDate;

            checkbox = '<input type="checkbox" name="check" class="check checked_bg" checked>';
            operateBtn = '<div class="btn_edit">修改</div><div class="btn_cancle">取消</div>'
        } else {
            operateBtn = '<div class="btn_edit">修改</div>';
        }
        var examRequestStr = ''
        if (examRequest.ProcedureName.split(';').length) {
            var arr = examRequest.ProcedureName.split(';');
            $.each(arr, function (i, n) {
                examRequestStr = examRequestStr + '<p>' + arr[i] + ' </p>';
            })
        } else {
            examRequestStr = '<p>' + examRequest.ProcedureName + ' </p>';
        }

        return '<div class="clinic_main">' +
                    '<div class="clinic_list">' +
                        ' <ul>' +
                            '<li class="clinic_list_check">' + checkbox + '</li>' +
                            '<li class="clinic_list_name clinic_list_ServiceSectID">' +
                                '<span>' + examRequest.ServiceSectID + ' </span>' +
                            '</li>' +
                            '<li class="clinic_list_name clinic_list_ServiceSectName">' + examRequestStr + '</li>' +
                            '<li class="clinic_list_time">预约时间：<span class="schedule_time scheduleDate">' + scheduleDate + '</span><span class="schedule_time scheduleTime" style="padding-left:20px;">' + scheduleTime + '</span></li>' +
                            '<li class="clinic_list_btn">' + operateBtn + '</li>' +
                        '</ul>' +
                        '<div id="time_container_' + examRequest.PlacerOrderNO + '" class="time_container"></div>' +
                    '</div>' +
                '</div>';
    }

    var pageEventInit = function () {
        //选中某一条数据
        $("#outPaitientContainer").on('click', '.check', checkOneRow);

        //全选取消全选
        $("#outPaitientContainer").on('click', '.check_all', checkAll);

        //取消预约
        $('#outPaitientContainer').on('click', '.btn_cancle', cancelSchedule);

        //打印
        $('.clinic_foot').on('click', '.btn_print', print);

        //修改预约
        $('#outPaitientContainer').on('click', '.btn_edit', edit);

        //关闭时间按钮
        $('#outPaitientContainer').on('click', '.closed', closeSchedule);

        //时间选择
        $('#outPaitientContainer').on('click', '.technology_table  tr td', selectTime);
        //选择不同的地方
        $('#outPaitientContainer').on('click', '.chose_palce', differntPlace);

        //确认预约
        $('#saveMulti').on('click', saveMultiExamSchedule);

        $('#btnBack').on('click', back);
    };

    var checkOneRow = function () {
        var $this = $(this);
        var isChecked = $this.prop('checked');
        if (isChecked) {
            $this.addClass('checked_bg');
        } else {
            $this.removeClass('checked_bg')
        }

        printNum();
    };

    var checkAll = function () {
        var $this = $(this);
        var checkArr = $('#outPaitientContainer .check');
        if ($('.check_all').closest('label').find('span').text() == '取消全选') {
            $('.check_all').closest('label').find('span').text('全选');
            $('.check_all').closest('label').find('input').removeClass('checked_bg');
            $('.btn_print ').addClass('btn_no_print');
            checkArr.each(function (i) {
                checkArr.eq(i).removeClass('checked_bg')
            })
        } else {
            $('.check_all').closest('label').find('span').text('取消全选');
            $('.btn_print ').removeClass('btn_no_print');
            $('.check_all').closest('label').find('input').addClass('checked_bg');
            checkArr.each(function (i) {
                checkArr.eq(i).addClass('checked_bg')
            })
        }

        printNum();
    };

    var edit = function () {
        var $this = $(this);
        var placerorderno = $this.closest('.clinic_div').data('placerorderno');
        editSchedule(placerorderno);
    };

    var closeSchedule = function () {
        $(this).closest('.time_container_div').remove();
    };

    var back = function () {
        $('#' + options.thisContainer).hide();
        $('#' + options.backContainer).show();

        if (options.backCallback) {
            options.backCallback();
        }
    };

    //取消预约
    var cancelSchedule = function () {
        var $this = $(this);
        schedule.comfirm('是否取消预约', function () {
            var placerOrderNO = $this.closest('.clinic_div').data("placerorderno");

            schedule.cancelSchedule({
                PlacerOrderNO: placerOrderNO
            }, function () {
                var $row = $('#' + placerOrderNO);

                $.each(schedule.examRequestList, function (i, n) {
                    if (n.PlacerOrderNO == placerOrderNO) {
                        n.ScheduleResourceID = '';
                        n.ScheduleResourceName = '';
                        n.ScheduleStartDate = '';
                        n.ScheduleEndDate = '';
                        n.ScheduleStatus = 1;
                        n.ScheduleFlag = false;

                        $('#' + placerOrderNO).html(appendScheduleRow(n));

                        return false;
                    }
                });

                printNum();
            });
        });
    };

    //打印条数
    var printNum = function () {
        printArr = [];
        var checkArr = $('#outPaitientContainer .checked_bg');
        $.each(checkArr, function (i) {
            var cancle_btn = checkArr.eq(i).closest('.clinic_div').find('.btn_cancle');
            if (cancle_btn.length) {
                var placerorderno = checkArr.eq(i).closest('.clinic_div').data('placerorderno');
                printArr.push({ PlacerOrderNO: placerorderno });
            }
        });
        $('.print_num').text(printArr.length);
        if (printArr.length) {
            if (printArr.length == checkArr.length) {
                $('.check_all').addClass('checked_bg');
                $('.check_all').closest('label').find('span').text('取消全选');
            }
            $('.btn_print').removeClass('btn_no_print')
        } else {
            $('.check_all').removeClass('checked_bg');
            $('.check_all').closest('label').find('span').text('全选');
            $('.btn_print').addClass('btn_no_print')
        }
    };

    //打印
    var print = function () {
        var printNum = printArr.length;
        $.each(printArr, function (i, n) {
            setTimeout(function () {
                schedule.print(n);
            }, 2000);
        });
        if (printNum == 0) {
            schedule.alert('请选择要打印的预约!');
        }
    };

    //修改
    var editSchedule = function (placerorderno) {
        var relateExamRequestList = [];
        $.each(schedule.examRequestList, function (i, n) {
            if (n.PlacerOrderNO == placerorderno) {
                scheduleExamRequest = n;
            } else {
                if (n.ScheduleStartDate && n.ScheduleEndDate) {
                    relateExamRequestList.push(n);
                }
            }
        });
        schedule.getScheduleInfo(scheduleExamRequest, relateExamRequestList, '', "", getScheduleInfoCallback);
        $('.time_container').html('');
        $('#time_container_' + placerorderno).html($('#timeTemple').html());
        $('#time_container_' + placerorderno).find('.date_chose').attr('id', "date_" + placerorderno);
        choseTime(placerorderno);
    };

    //获取单个申请的预约资源排班
    var getScheduleInfoCallback = function (data) {
        var resourceHtml = '';
        $.each(data.ScheduleArrangeResourceInfoList, function (i, n) {
            var border_right_none = (i == data.ScheduleArrangeResourceInfoList.length - 1) ? "" : "border_right_none";

            if (n.ResourceUID == data.ResourceUID) {
                resourceHtml += '<li class="' + border_right_none
                                  + ' chose_palce    actived" data-resourceuid="' + n.ResourceUID + '" data-location="' + n.ResourceLocation + '">'
                                  + n.ResourceName + '</li>';

                if (n.ScheduleArrangeDateInfoList.length == 1) {
                    var dateInfo = n.ScheduleArrangeDateInfoList[0];
                    var arrangeDay = imcis.convertDateFromJson(dateInfo.ArrangeDay, true);
                    $('#date_' + scheduleExamRequest.PlacerOrderNO).val(arrangeDay); //推荐日期
                    var timeList = dateInfo.ScheduleArrangeTimeInfoList; //推荐日期下的时间数组
                    addGroupTime(timeList);
                }
            } else {
                resourceHtml += '<li class="' + border_right_none + '  chose_palce" data-resourceuid="' + n.ResourceUID + '">' + n.ResourceName + '</li>'; //不同地方
            }
        });

        $('#time_container_' + scheduleExamRequest.PlacerOrderNO + ' .layui-tab-title').html(resourceHtml);
        $('#time_container_' + scheduleExamRequest.PlacerOrderNO + ' .time_container_div').show();
    };

    //时间组添加时间段
    var addGroupTime = function (timeList) {
        var scheduleArrange = { groupList: [] };

        for (var i = 0; i < timeList.length; i++) {
            if (!scheduleArrange[timeList[i].GroupName]) {
                scheduleArrange[timeList[i].GroupName] = {
                    times: []
                };
                scheduleArrange.groupList.push(timeList[i].GroupName);
            }
            scheduleArrange[timeList[i].GroupName].times.push(timeList[i]);
        }

        var html = "";
        for (var i = 0; i < scheduleArrange.groupList.length; i++) {
            var groupName = scheduleArrange.groupList[i];
            var times = scheduleArrange[groupName].times;

            var totalStr = '<table class="technology_table " border="0" cellspacing="1" cellpadding="0" id="time_detail_container">';
            var addTdStr = '';

            if (times.length % 8 == 0) { times = scheduleArrange[groupName].times; } else {
                var i = 8 - ((times.length) % 8);
                for (var j = 0; j < i; j++) {
                    addTdStr += '<td  class="schedule-banlk " style=" width: 12.5%;"></td>'
                }
                addTdStr += '</tr>';
            }
            for (var i = 0; i < times.length; i++) {
                var temp = '';
                var time = times[i].StartTime + "-" + times[i].EndTime;
                switch (times[i].ScheduleTimeStatus) {
                    case 3:
                    case 4:
                        //不可预约时间           
                        temp += '<td class="schedule-disable" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" >' + time + '</td>';
                        break;
                    case 0: //选中的时间
                        temp += '<td class="schedule-current" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" >' + time + '</td>';
                        break;
                    case 1:
                        //选中的时间
                        temp += '<td class="schedule-finish" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" >' + time + '</td>';
                        break;
                    default:
                        //可预约时间
                        temp += '<td class=" schedule-enable" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" >' + time + '</td>';
                        break;
                }

                if (i == 0 || i % 8 == 0) {
                    totalStr = totalStr + '<tr>' + temp;
                } else if ((i + 1) % 8 == 0) {
                    totalStr = totalStr + temp + '</tr>'
                    temp = '';
                } else {
                    totalStr = totalStr + temp;
                }
            }

            html += totalStr + addTdStr + '</table>';
        }
        $('#time_container_' + scheduleExamRequest.PlacerOrderNO + ' .layui-tab-item').html(html);
    };

    //选中时间
    var selectTime = function () {
        if ($(this).hasClass('schedule-disable')) {
            return;
        } else if ($(this).hasClass('schedule-enable')) {
            $('#time_detail_container .schedule-current').removeClass('schedule-current').addClass('schedule-enable');
            $(this).addClass('schedule-current');

        } else if ($(this).hasClass('schedule-finish')) {
            $('#time_detail_container .schedule-current').removeClass('schedule-current');
        }

        var $source = $('#time_container_' + scheduleExamRequest.PlacerOrderNO + ' .layui-tab-title .actived');
        scheduleExamRequest.ScheduleResourceUID = $source.data('resourceuid');
        scheduleExamRequest.ScheduleResourceName = $source.text();
        scheduleExamRequest.ObservationLocation = $source.data('location');

        var scheduleDate = $('#date_' + scheduleExamRequest.PlacerOrderNO).val();
        var scheduleTime = $(this).text();
        scheduleExamRequest.ScheduleStartDate = scheduleDate + " " + scheduleTime.split('-')[0];
        scheduleExamRequest.ScheduleEndDate = scheduleDate + " " + scheduleTime.split('-')[1];
        scheduleExamRequest.Quantity = $(this).data('quantity');

        if (scheduleExamRequest.ScheduleFlag) {
            if (scheduleExamRequest.ScheduleResourceName == scheduleExamRequest.OriginalScheduleResourceName &&
                        scheduleExamRequest.ScheduleStartDate == scheduleExamRequest.OriginalScheduleStartDate &&
                        scheduleExamRequest.ScheduleEndDate == scheduleExamRequest.OriginalScheduleEndDate) {
                scheduleExamRequest.ChangeFlag = false;
            } else {
                scheduleExamRequest.ChangeFlag = true;
            }
        }
        $('#' + scheduleExamRequest.PlacerOrderNO + ' .scheduleDate').text(scheduleDate);
        $('#' + scheduleExamRequest.PlacerOrderNO + ' .scheduleTime').text(scheduleTime);
    };

    //不同的检查地点
    var differntPlace = function () {
        var $this = $(this);
        $('.actived').removeClass('actived');
        $this.addClass('actived');
        var resourceuid = $this.data('resourceuid');
        var placerOrderNO = $this.closest('.clinic_div').data("placerorderno");
        $('#time_container_' + scheduleExamRequest.PlacerOrderNO + ' .layui-tab-item').html("");
        schedule.getScheduleInfo(scheduleExamRequest, [], resourceuid, "", function (data) {
            $.each(data.ScheduleArrangeResourceInfoList, function (i, n) {
                if (n.ScheduleArrangeDateInfoList.length == 1) {
                    var dateInfo = n.ScheduleArrangeDateInfoList[0];
                    var arrangeDay = imcis.convertDateFromJson(dateInfo.ArrangeDay, true);
                    $('#date_' + scheduleExamRequest.PlacerOrderNO).val(arrangeDay); //推荐日期

                    var timeList = dateInfo.ScheduleArrangeTimeInfoList; //推荐日期下的时间数组
                    addGroupTime(timeList);
                }
            });
        });
    };

    //时间选择
    var choseTime = function (placerorderno) {
        //时间选择
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            var start = {
                min: laydate.now()
                  , max: '2099-06-16 23:59:59'
                  , istoday: false
                  , choose: function (datas) {
                      schedule.startDate = datas;
                      editSchedule(placerorderno);
                  }
            };

            document.getElementById('date_' + placerorderno).onclick = function () {
                start.elem = this;
                laydate(start);
            }

        });
    };

    //一键预约多个检查申请
    var saveMultiExamSchedule = function () {
        schedule.saveExamSchedule(null, function (data) {
            schedule.getExamRequestScheduleInfoList(getExamRequestScheduleInfoListCallback);
        });
    };
};
